package com.dmall.algorithm.chapter01;

import java.util.Stack;

public class Leetcode20 {

    public boolean isValid(String s) {
        if (s == null || "".equalsIgnoreCase(s.trim())) {
            return true;
        }
        Stack<Character> stack = new Stack<>();
        char[] chars = s.toCharArray();
        if (chars[0] == ')' || chars[0] == ']' || chars[0] == '}') {
            return false;
        }
        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            if (c == '(' || c == '[' || c == '{') {
                stack.push(c);
            } else {
                if (stack.empty()) {
                    return false;
                }
                if (c == ')') {
                    char pop = stack.pop();
                    if (pop != '(') {
                        return false;
                    }
                } else if (c == ']') {
                    char pop = stack.pop();
                    if (pop != '[') {
                        return false;
                    }
                } else if (c == '}') {
                    char pop = stack.pop();
                    if (pop != '{') {
                        return false;
                    }
                }
            }
        }
        return stack.empty();
    }
}
